package com.zgscwjm.taobaphelper;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.zgscwjm.taobaphelper.data.HotWifi;
import com.zgscwjm.taobaphelper.exutils.StringUtils;
import com.zgscwjm.taobaphelper.ui.ar;
import com.zgscwjm.taobaphelper.xp.FileManager;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import static com.zgscwjm.taobaphelper.BaseConfig.b;

/**
 * 用户操作选择页面 对应原---UserOperationActivtiy
 * 主页面
 */
public class MainActivity extends Activity {

    // TODO: 17-3-1 这里的地址要替换
    private static final String A = (BaseConfig.baseUrl + "");

    //对应原来的B
    private static List list = null;

    //对应原来的C
    private static InputMethodManager inputManager=null;
    public static boolean E=false;

    // FIXME: 17-2-28 这里应该是Android系统的
    private static String G= "/dev/input/event";;

    /**
     *这里源代码是private 现在因为aw文件要静态引用,所有改成public
     */
    public static String H="";

    private static  int[] I = new int[]{3,0,1,2,4,5,6,7,8,9};

    // FIXME: 17-2-28 接口地址
    public static final String q = BaseConfig.baseUrl+"";
    public static final String r=BaseConfig.baseUrl+"";;
    public static String s="";
    public static ProgressDialog progressDialog=null;//原变量t
    // FIXME: 17-2-28 接口地址
    private static final String u=BaseConfig.baseUrl+"";;
    private static final String v=BaseConfig.baseUrl+"";;
    private static final String w=BaseConfig.baseUrl+"";;
    private static final String x=BaseConfig.baseUrl+"";;
    private static final String y=BaseConfig.baseUrl+"";;
    private static final String z=BaseConfig.baseUrl+"";;

    /**
     * 应该是用来表示 匹配手机
     */
    public boolean D = false;

    public int F=0;

    private Handler J = new ar(this);;
    TextView a = null;

    /**
     * 对应源来的b
     */
   public TextView tv_username = null;

    /**
     * 对应原来的c
     */
    TextView tv_signture = null;

    /**
     * 对应原来的d 
     */
 public    TextView tv_currentUserPoints = null;

    /**
     * 对应原来的e
     */
   public TextView tv_errorTip = null;

    //对应原来的f
   public TextView tv_taobaoversion = null;
    /**
     * 对应原来的g
     */
   public TextView tv_currentVersion = null;
    /**
     * 对应原来的h
     */
    TextView tv_inputMethod = null;

    /**
     * 对应原来的i
     */
   public TextView tv_wangwangName = null;

    /**
     * 对应原来的j
     */
    Button btn_start = null;

    /**
     * 对应原来的k
     */
    Button btn_stop = null;

    /**
     * 对应原来的l
     */
    Button btn_loginout = null;

    /**
     * 对应原来的m
     */
    Button btn_update = null;

    /**
     * 对应原来的n
     */
    Button btn_taobaoupdate = null;

    /**
     * 对应原来的o
     */
    Button btn_inputMethod = null;

    /**
     * 对应原来的p
     */
    Button btn_binderwang = null;






    /**
     * 得到版本号 -------对应原a方法
     * @param context
     * @param packgeName
     * @return
     */
    public static String getVersionName(Context context,final String packgeName){
        try{
            return context.getPackageManager().getPackageInfo(packgeName,0).versionName;
        }catch (Exception ex){
            Log.e("MainActivity",ex.getMessage());
            return "";
        }
    }

    /**
     * 显示信息--------对应原来的a方法
     * @param title
     * @param content
     */
    public void showMessage(String title,String content){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(title);
        builder.setMessage(content);
        builder.setPositiveButton("是",new click_dialog(this));
        builder.show();
    }

    /**
     * 得到淘宝的版本号 ---- 对应原方法b
     * @param context
     * @return
     */
    public static String getTaoBaoVersionName(final Context context){
        try{
            return context.getPackageManager().getPackageInfo("com.taobao.taobao",0).versionName;
        }catch (Exception ex){
            Log.e("MainActivity",ex.getMessage());
            return StringUtils.EMPTY;
        }
    }

    // FIXME: 17-3-1 这里应该是启动一个比较关键的服务
    public void c(MainActivity mainActivity){
        Intent intent = new Intent(mainActivity,NetflowMissionService.class);
        Bundle bundle = new Bundle();
        bundle.putInt("setp",9001);
        intent.putExtras(bundle);
        mainActivity.startService(intent);
        mainActivity.startService(new Intent(mainActivity,CheckMissionRunService.class));
        mainActivity.finish();
    }

    /**
     * 绑定小号 对应原来d方法
     * @param mainActivity
     */
    public static void showBinderWang(MainActivity mainActivity){
        EditText editText = new EditText(mainActivity);
        editText.setFocusable(true);
        editText.setText(s);
        AlertDialog.Builder builder = new AlertDialog.Builder(mainActivity);
        builder.setTitle("登录小号").setView(editText);
        builder.setPositiveButton("保存",new an(mainActivity,editText));
        builder.setNegativeButton("取消",null);
        builder.show();

    }

    public final void a(){
        new Thread(new at(this)).start();
    }

    public final void b(){
        WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        //从简单意义上而言，BSSID是等价于MAC地址的。
        String bssid = wifiManager.getConnectionInfo().getBSSID();
        FileManager.writeContent(FileManager.bssidPath,bssid);
        List<ScanResult> scanResults = wifiManager.getScanResults();
        list = new ArrayList();
        for (ScanResult scanResult : scanResults) {
            String sc_bssid = scanResult.BSSID;
            String sc_ssid = scanResult.SSID;
            String sc_empty = StringUtils.EMPTY;
            System.out.println("bssid:"+bssid+", ssid"+sc_ssid+", cap:"+sc_empty);
            list.add(new HotWifi(sc_ssid,sc_bssid,sc_empty));
        }
        new Thread(new au(this)).start();
    }
    public final void c(){
        new Thread(new aw()).start();
    }
    public final void d() {
        new Thread(new ay(this)).start();
    }


    /**
     * 检测当前默认输入法是否是自定义的输入 对应原来的g方法
     * @return
     */
    public final boolean checkInputMethod(){
        // FIXME: 17-3-1 这里Utf7ImeService替换成自己的输入法服务
        return Settings.Secure.getString(getContentResolver(),"default_input_method").contains("Utf7ImeService");
    }
    public final void h() {
        new Thread(new bc(this)).start();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //去掉锁屏
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD,WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
        setContentView(R.layout.activity_main);

        this.tv_username = (TextView) findViewById(R.id.act_main_tv_lable_username);
        this.tv_signture = (TextView) findViewById(R.id.act_main_tv_signature);

        this.tv_errorTip = (TextView) findViewById(R.id.act_main_tv_errortip);
        this.tv_taobaoversion = (TextView) findViewById(R.id.act_main_tv_taobaoversion);
        this.tv_currentVersion = (TextView) findViewById(R.id.act_main_tv_currentversion);
        this.tv_inputMethod = (TextView) findViewById(R.id.act_main_tv_inputmethod);

        this.tv_currentUserPoints = (TextView) findViewById(R.id.act_main_tv_currentintegral);

        this.tv_wangwangName = (TextView) findViewById(R.id.act_main_tv_wangwangname);


        this.a = (TextView) findViewById(R.id.act_main_tv_lable_username);
        this.a.setOnClickListener(new am(this));

        /**
         * BRAND// android系统定制商
         * MODEL // 版本
         */
        H= Build.BRAND+"_"+Build.MODEL;

        // TODO: 17-3-1 PushManager.startWork(getApplicationContext(),0,"");
        inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

        progressDialog = new ProgressDialog(this);

        progressDialog.setMessage("版本获取中....");

        progressDialog.setProgressStyle(0);

        progressDialog.show();

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount()==0)
        {
            finish();
        }
        return false;
    }



    @Override
    protected void onStart() {

        // FIXME: 17-3-1 z这里到时候要翻译
        boolean z;
        super.onStart();
        E = false;
        int sdkVersion = Integer.valueOf(Build.VERSION.SDK).intValue();
        if (sdkVersion<18){
            showMessage("手机版本太低", "检测到您的手机SDK为:" + sdkVersion + "，请使用android4.3或4.3以上的手机版本！");
            z = false;
        }else if (!new File("/system/xbin/su").exists()&& !new File("/system/bin/su").exists()) {
            showMessage("手机未root", "检测到您的手机没有root，或者没有root正确，请重新root后再使用！");
            z=false;
        }else if (StringUtils.isEmpty(a.c(" ls /dev/input"))){
            //这里的a类应该是来进行执行shell命令的
            showMessage("手机未root", "检测到您的手机没有root，或者没有root正确，请重新root后再使用！");
            z=false;
        }else if (new File("/system/bin/uiautomator").exists()||new File("/system/xbin/uiautomator").exists()){
            a.a();
            if (StringUtils.isEmpty(a.a(getApplicationContext()))){
                showMessage("设备ID无效","该手机设备信息无效,如IMEI等。请更换其他版本！");
                z = false;
            }else{
                new Thread(new aq(this)).start();
                z = true;
            }
        }else{
            showMessage("手机版本不兼容","检测到您的手机不兼容，请更换其他4.3或其以上版本的android系统");
            z = false;
        }

        if (z){
            this.btn_inputMethod = (Button) findViewById(R.id.act_main_btn_inputmethod);
            this.btn_inputMethod.setOnClickListener(new av(this));
            //原---if (v.dataException(this)) {
            if (BaseConfig.checknet(this)){
                //todo 这里的b肯定不是ui下面的b,应该是auto下面的b
                if (StringUtils.isEmpty(b.b) && StringUtils.isEmpty(FileManager.findDBInfo(this,FileManager.CookiesLoginParam))){
                    z = false;
                }else{
//                    Object findDBInfo = FileManager.findDBInfo(this, FileManager.UserNameParam);
                    String findDBInfo = FileManager.findDBInfo(this, FileManager.UserNameParam);
                    if (StringUtils.isEmpty(findDBInfo)){
                        new Thread(new bd(this)).start();
                        z = true;
                    }else{
                        this.tv_username.setText(findDBInfo);
                        FileManager.saveDBInfo(this,FileManager.UserNameParam,findDBInfo);
                        z = true;
                    }
                }

                if (z){
                    String readKey = FileManager.readKey(this);
                    if (StringUtils.isEmpty(readKey)){
                        this.tv_signture.setText("获取手机唯一码失败，请重新登录！");
                    }else{
                        this.tv_signture.setText(" (" + readKey + ")");
                    }

                    new Thread(new as(this)).start();
                    new Thread(new az(this)).start();
                    if (StringUtils.isEmpty(getVersionName((Context)this,"com.taobao.taobao"))){
                        this.tv_taobaoversion.setText("未安装淘宝!");
                    }else{
                        new Thread(new ao(this)).start();
                    }
                    new Thread(new ap(this)).start();
                    new Thread(new ax(this)).start();
                    new Thread(new ay(this)).start();
                    new Thread(new at(this)).start();
                    this.btn_start = (Button) findViewById(R.id.act_main_btn_start);
                    this.btn_start.setOnClickListener(new click_startservice(this));

                    this.btn_stop = (Button) findViewById(R.id.act_main_btn_stop);
                    this.btn_stop.setOnClickListener(new click_stopservice(this));

                    this.btn_binderwang = (Button) findViewById(R.id.act_main_btn_binderwangwang);
                    this.btn_binderwang.setOnClickListener(new click_showbinderwang(this));

                    this.btn_loginout = (Button) findViewById(R.id.act_main_btn_loginout);
                    this.btn_loginout.setOnClickListener(new click_exit(this));

                    this.btn_update = (Button) findViewById(R.id.act_main_btn_update);
                    this.btn_update.setOnClickListener(new click_update(this));

                    this.btn_taobaoupdate = (Button) findViewById(R.id.act_main_btn_taobaoupdate);
                    this.btn_taobaoupdate.setOnClickListener(new click_taobaoupdate(this));
                    return;
                }
                progressDialog.dismiss();
                startActivity(new Intent(this,LoginActivity.class));
                finish();
                return;
            }
            progressDialog.dismiss();
            return;
        }

        progressDialog.dismiss();
    }

    protected void onStop(){
        super.onStop();
        E = true;
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        List<InputMethodInfo> enabledInputMethodList = inputManager.getEnabledInputMethodList();
        String str_DefaultInputMethod = Settings.Secure.getString(getContentResolver(),"default_input_method");
        for (InputMethodInfo inputMethodInfo : enabledInputMethodList) {
            if (inputMethodInfo!=null && str_DefaultInputMethod.equals(inputMethodInfo.getId())) {
                this.tv_inputMethod.setText(inputMethodInfo.loadLabel(getPackageManager()));
                // FIXME: 17-3-1 替换成自己的服务
                if (str_DefaultInputMethod.contains("Utf7ImeService")){
                    CharSequence findDBInfo = FileManager.findDBInfo(getApplicationContext(),FileManager.ServerStopParam);
                    if (StringUtils.isEmpty(findDBInfo.toString())){
                        String str_currentInputMethod = this.tv_inputMethod.getText().toString();
                        if (!StringUtils.isEmpty(str_currentInputMethod) &&str_currentInputMethod.equals("请先修改输入法为[手机流量专用]输入法")){
                            this.tv_inputMethod.setText("");
                        }
                    }else{
                        this.tv_inputMethod.setText(findDBInfo);
                    }
                }else {
                    this.tv_errorTip.setText("请先修改输入法为[手机流量专用]输入法");
                }
            }
        }
    }
    public final void f(){
        new Thread(new bb(this)).start();
    }



}
